<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="角色" prop="userType">
        <el-select v-model="queryParams.userType" placeholder="请选择角色" clearable>
          <el-option
            v-for="dict in userTypes"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单位名称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入单位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="经济带" prop="economic">
        <el-select v-model="queryParams.economic" placeholder="请选择" clearable>
          <el-option
            v-for="dict in dict.type.economic_belt"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-input
          v-model="queryParams.city"
          placeholder="请输入城市"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审批状态" prop="state">
        <el-select v-model="queryParams.state" clearable placeholder="请选择">
          <el-option
            v-for="dict in status"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-select v-model="queryParams.sort" clearable placeholder="请选择">
          <el-option
            v-for="dict in sortType"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['information:user:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['information:user:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['information:user:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" height="600" fixed>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="用户ID" align="center" prop="userId"/>
      <el-table-column label="用户名称" align="center" prop="nickName"/>
<!--      <el-table-column label="用户身份 " align="center" prop="userType">-->
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="dict.type.user_type" :value="scope.row.userType"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="注册时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180"/>
      <el-table-column label="联系电话" align="center" prop="phonenumber"/>
      <el-table-column label="经济带" align="center" prop="economic"/>
      <el-table-column label="城市" align="center" prop="city"/>
      <el-table-column label="审批状态" align="center" prop="state" width="180">
        <template slot-scope="scope">
          <div v-for="item in status" v-if="item.value === scope.row.state">
            <span>{{ item.label }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column width="250" fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.state==0||scope.row.state==-1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAudit(scope.row)"
            v-hasPermi="['information:user:process']"
          >审核
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['information:user:edit']"
          ><span v-if="$store.getters.userId===scope.row.userId">编辑</span>
            <span v-if="$store.getters.userId!==scope.row.userId">查看</span>
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['information:user:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleResetPwd(scope.row)"
            v-hasPermi="['information:user:edit']"
          >修改密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="759px" :close-on-click-modal='false' append-to-body center>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="联系电话" prop="phonenumber">
          <el-input class="kind" :disabled="title !== '添加供给方'" v-model="form.phonenumber" placeholder="请输入联系电话"/>
        </el-form-item>
        <el-form-item label="姓名" prop="contactName">
          <el-input class="kind" v-model="form.contactName" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="职务信息" prop="remark">
          <el-input class="kind" type="textarea" v-model="form.remark" placeholder="请输入职务信息"/>
        </el-form-item>
        <el-form-item label="关联园区" prop="park">
          <el-select class="kind" v-model="selectList" multiple placeholder="请选择园区">
            <el-option
              v-for="dict in parkList"
              :key="dict.id"
              :label="dict.label"
              :value="dict.value+''"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所在地" prop="province" class="business">
          <!--          <el-input v-model="form.provinceId" placeholder="请输入省份ID" />-->
          <el-select v-model="form.province" placeholder="请选择省份"
                     @change="getCityList(form.province)" style="width: 30%">
            <el-option
              v-for="dict in provinces"
              :key="dict.name"
              :label="dict.name"
              :value="dict.name"
            />
          </el-select>
          <el-select v-model="form.city" placeholder="请选择城市"
                     :disabled="form.province==null||form.province===''" @change="getAreaList(form.city)"
                     style="width: 30%">
            <el-option
              v-for="dict in citys"
              :key="dict.name"
              :label="dict.name"
              :value="dict.name"
            />
          </el-select>
          <el-select v-model="form.area" placeholder="请选择区域" :disabled="form.city==null||form.city===''"
                     style="width: 30%" clearable>
            <el-option
              v-for="dict in areas"
              :key="dict.name"
              :label="dict.name"
              :value="dict.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单位名称" prop="nickName">
          <el-input class="kind" v-model="form.nickName" placeholder="请输入单位名称"/>
        </el-form-item>
        <el-form-item label="角色" prop="userType">
          <el-select class="kind" :disabled="title !== '添加供给方'" v-model="form.userType" placeholder="请选择角色">
            <el-option
              v-for="dict in userTypes"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="经济带" prop="economic">
          <el-select class="kind" v-model="form.economic" placeholder="请选择">
            <el-option
              v-for="dict in dict.type.economic_belt"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <image-upload :limit="1" v-model="form.avatar"/>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="title==='添加用户'" label="密码" prop="password">
          <el-input class="kind" v-model="form.password" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="审核备注" v-if="form.state!=-1&&form.state!=0" prop="epprovalNote">
          <el-input class="kind" disabled type="textarea" v-model="form.epprovalNote" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="$store.getters.userId===form.userId||title=='添加供给方'" @click="submitForm">确
          定
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="审核" :visible.sync="open2" width="600px" :close-on-click-modal='false' append-to-body center>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="状态" prop="state">
          <el-select class="kind" v-model="form.state" placeholder="请选择状态">
            <el-option
              v-for="dict in status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="epprovalNote">
          <el-input class="kind" type="textarea" v-model="form.epprovalNote" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addUser, delUser, getUser, listUser, updateUser} from "@/api/information/user";
import {listAllPark} from "@/api/information/park";
import {resetUserPwd} from "@/api/system/user";
import {listCity} from "@/api/business/businessIntro";

export default {
  name: "User",
  dicts: ['user_type', 'sys_user_sex', 'economic_belt'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      userTypes: [
        {
          value: "01",
          label: "供给方政府"
        },
        {
          value: "02",
          label: "供给方产权单位"
        },
        {
          value: "03",
          label: "供给方运营单位"
        },
      ],
      sortType: [
        {
          value: 0,
          label: "按时间倒序"
        },
        {
          value: 1,
          label: "按时间正序"
        },
      ],
      status: [
        {
          value: -1,
          label: "未提交"
        },
        {
          value: 0,
          label: "待审批"
        },
        {
          value: 1,
          label: "审批通过"
        },
        {
          value: 2,
          label: "审批失败"
        },
      ],
      parkList: [],
      selectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        userName: null,
        nickName: null,
        userType: null,
        email: null,
        phonenumber: null,
        sex: null,
        avatar: null,
        password: null,
        status: null,
        loginIp: null,
        loginDate: null,
        sort: null,
        state: null,
        park: null,
        economic: null,
        address: null,
        area: null,
        city: null,
        province: null
      },
      // 表单参数
      form: {},
      // 省列表
      provinces: [],
      // 市列表
      citys: [],
      // 区列表
      areas: [],
      // 表单校验
      rules: {
        userName: [
          {required: true, message: "用户账号不能为空", trigger: "blur"}
        ],
        sex: [
          {required: true, message: "性别不能为空", trigger: "blur"}
        ],
        nickName: [
          {required: true, message: "单位名称不能为空", trigger: "blur"},
          {max: 100, message: '长度必须小于 100', trigger: 'blur'}
        ],
        userType: [
          {required: true, message: "角色不能为空", trigger: "blur"}
        ],
        phonenumber: [
          {required: true, message: "请输入手机号", trigger: "blur"},
        ],
        password: [
          {required: true, message: "密码不能为空", trigger: "blur"},
          {max: 20, message: '长度必须小于 20', trigger: 'blur'}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getSpace();
    this.getprovinceList();
  },
  methods: {
    /** 查询省列表 */
    getprovinceList() {
      var parentId = 0;
      listCity(parentId).then(res => {
        // console.log("AAA",res)
        this.provinces = res.data;
      })
    },
    //查询市列表
    getCityList(provinceId) {
      //console.log("BBB",provinceId)
      var id = null;

      for (let i = 0; i < this.provinces.length; i++) {
        if (provinceId === this.provinces[i].name) {
          id = this.provinces[i].id
        }
      }
      listCity(id).then(res => {
        this.citys = res.data;
      })
    },
    //查询市列表
    getCityList2(provinceId) {
      //console.log("BBB",provinceId)
      var id = null;

      for (let i = 0; i < this.provinces.length; i++) {
        if (provinceId === this.provinces[i].name) {
          id = this.provinces[i].id
        }
      }
      listCity(id).then(res => {
        this.citys = res.data;
        if (this.form.city != null && this.form.city !== "" && this.form.city !== "null") {
          this.getAreaList(this.form.city)
        }
      })
    },
    //查询区列表
    getAreaList(cityId) {
      var id = null;
      for (let i = 0; i < this.citys.length; i++) {
        if (cityId === this.citys[i].name) {
          id = this.citys[i].id
        }
      }
      listCity(id).then(res => {
        this.areas = res.data;
        console.log(res.data)
      })
    },
    getSpace() {
      listAllPark().then(res => {
        this.parkList = res.park
      });
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.open2 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        deptId: null,
        userName: null,
        nickName: null,
        userType: null,
        email: null,
        phonenumber: null,
        sex: null,
        avatar: null,
        password: null,
        status: null,
        delFlag: null,
        loginIp: null,
        loginDate: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        park: null,
        state: -1,
        economic: null,
        address: null,
        area: null,
        city: null,
        province: null,
        contactName: null,
        approvalNote: null,
        epprovalNote: null
      };
      this.resetForm("form");
      this.selectList = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加供给方";
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
      }).then(({value}) => {
        resetUserPwd(row.userId, value).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => {
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids
      getUser(userId).then(response => {
        this.form = response.data;
        if (response.data.park != null && response.data.park !== '') {
          this.selectList = response.data.park.split(",");
        }
        if (this.form.province != null && this.form.province !== "") {
          this.getCityList2(this.form.province)
        }
        this.open = true;
        if (this.$store.getters.userId !== this.form.userId) {
          this.title = "供给方详情";
        } else {
          this.title = "修改供给方";
        }
      });
    },
    /** 审核按钮操作 */
    handleAudit(row) {
      this.reset();
      const id = row.userId
      getUser(id).then(response => {
        this.form = response.data;
        this.open2 = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.selectList.length !== 0) {
            for (let i = 0; i < this.selectList.length; i++) {
              if (i === 0) {
                this.form.park = this.selectList[i] + ","
              } else {
                this.form.park = this.form.park + this.selectList[i] + ","
              }
            }
            this.form.park = this.form.park.substring(0, this.form.park.length - 1)
          } else {
            this.form.park = ''
          }
          if (this.form.userId != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.open2 = false;
              this.getList();
            });
          } else {
            this.form.state = 1
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function () {
        return delUser(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('information/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.kind {
  width: 90%;
}
</style>
